package com.tozed.android.launcher.simpleui;

import com.tozed.android.launcher.R;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class SimpleBubbleView extends RelativeLayout
{
	private static final String TAG = "SimpleBubbleView";
	
	private static final String ADD_CONTACT_BG = "bg_add_contact";
	public static final String DEFAULT_BG = "bg_grey"; 		// 默认为灰色底背景
	private static final int FLAG_UPDATE_UNREAD = 4112;		// 更新未读消息
	private static final int UPDATE_UNREAD_DELAY = 100; 	// 延时时间
	
	public SimpleItemInfo info;		 // 应用数据信息
	private ImageView mAppIcon;		 // 应用图标
	private ImageView mAppIconBg;	 // 应用图标背景
	private int mAppIconHeight;		 // 应用图标高度
	private int mAppIconWidth;		 // 应用图标宽度
	private TextView mAppTitle; 	 // 应用标题
	private ImageView mRemoveInfo;	 // 长按时出现删除图标
	private TextView mUnreadMessage; // 未读消息文本
	private int mUnreadNum;			 // 未读消息数
	
	private Drawable mOnTouchDrawble;
	private Resources mResource;
	private Context mContext;
	
	private boolean mIsTouchMove = false;
	
	Runnable mDrawOutlineRunnable = new Runnable()
	{
		@Override
		public void run()
		{
			//Log.e(TAG,">>mDrawOutlineRunnable run...... isPressed=" + isPressed());
			if (!isPressed())
			      setPressed(true);
			
			 postInvalidate();
		}
	};
	
	Handler mPostDrawHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			if (FLAG_UPDATE_UNREAD == msg.what)
			{
				if (mUnreadNum <= 0){
					mUnreadMessage.setVisibility(View.GONE);
				} else {
					StringBuilder sb = new StringBuilder();
					sb.append(mUnreadNum);
					mUnreadMessage.setText(sb.toString());
					mUnreadMessage.setVisibility(View.VISIBLE);
				}
			}
			
			super.handleMessage(msg);
		}
	};
	
	public SimpleBubbleView(Context context){
		this(context, null);
	}

	public SimpleBubbleView(Context context, AttributeSet attrs){
		this(context, attrs, 0);
	}

	// CellLayout中包含的View视图,类WIN8色块
	public SimpleBubbleView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);
		
		mContext = context;
		mResource = mContext.getResources();
		
		Drawable defaultDrawable = mResource.getDrawable(R.drawable.icon_bg);
		
		mAppIconWidth = defaultDrawable.getIntrinsicWidth();
		mAppIconHeight = defaultDrawable.getIntrinsicHeight();
	}
	
	// 所有子视图在simple_bubble_view.xml中的SimpleBubbleView对象中放入
	// 当SimpleBubbleView中所有的子控件均被映射成xml后触发onFinishInflate
	/**
	 * 比如你 自定义一个view叫myView ,路径是，com.test.view.MyView,此view是继承LinearLayout，定义的布局文件是my_view.xml
	 *	里面内容是：
	 *	<com.test.view.MyView>
     *    	<xxxx />
	 *  </com.test.view.MyView>
	 *
	 *  当你在使用的时候，可以这样使用
	 *	MyView mv = (MyView)View.inflate (context,R.layout.my_view,null);
	 *	当加载完成xml后，就会执行那个方法。
	 */
	protected void onFinishInflate()
	{
		super.onFinishInflate();
		
		mAppIcon = ((ImageView) findViewById(R.id.simple_app_icon));
		mAppIconBg = ((ImageView) findViewById(R.id.simple_app_icon_bg));
		mRemoveInfo = ((ImageView) findViewById(R.id.simple_app_remove_view));
		mAppTitle = ((TextView) findViewById(R.id.simple_app_title));
		mUnreadMessage = ((TextView) findViewById(R.id.simple_app_unread_msg));
		
		mOnTouchDrawble = mResource.getDrawable(R.drawable.bg_pressed);
		
		if (SimpleUtilities.isMirrorLanguage())
			mUnreadMessage.setGravity(Gravity.RIGHT);
	}
	
	// 使位图平滑抗锯齿
	private Bitmap antiAlias(Bitmap oldBmp)
	{
		int width = oldBmp.getWidth();
		int heitht = oldBmp.getHeight();
		Paint paint = new Paint();
		
		paint.setAntiAlias(true);
		paint.setFilterBitmap(true);
		
		Bitmap newBmp = Bitmap.createBitmap(width, heitht, Bitmap.Config.ARGB_8888);
		Rect src = new Rect(0, 0, width, heitht);
		Rect dst = new Rect(0, 0, width, heitht);
		
		Canvas canvas = new Canvas(newBmp);
		canvas.drawBitmap(oldBmp, src, dst, paint);
		
		return newBmp;
	}
	
	private boolean checkChildView(){
		return (mAppIcon != null) && (mAppTitle != null) && (mAppIconBg != null);
	}
	
	// 画整个大的Cell View的轮廓
	private void drawBubbleOutline(Canvas canvas)
	{
		int width = getWidth();
		int height = getHeight();
		
		canvas.save();
		
		canvas.translate(mScrollX, mScrollY);
		mOnTouchDrawble.setBounds(0, 0, width, height);
		mOnTouchDrawble.draw(canvas);
		
		canvas.restore();
	}
	
	// 申请给BubbleView添加图标
	public void applyAddIconFromBubbleView(SimpleItemInfo itemInfo)
	{
		setBackgroundResource(mResource.getIdentifier("bg_grey", "drawable", "com.tozed.android.launcher")); // 配置背景资源
		
		if (checkChildView()){
			mAppIcon.setImageResource(R.drawable.ic_add);
			mAppTitle.setText(itemInfo.title);
		}
		
		info = itemInfo;
		setTag(itemInfo);
	}
	
	// 申请给BubbleView添加联系人快捷方式
	public void applyContactShortcutBubbleView(SimpleItemInfo itemInfo)
	{
		setBackgroundResource(mResource.getIdentifier("bg_add_contact","drawable","com.tozed.android.launcher"));// 配置背景资源
		
		itemInfo.itemType = SimpleLauncherSettings.SimpleFavorites.ITEM_TYPE_SHORTCUT;
		
		Bitmap maskBmp = SimpleUtilities.getMaskBitmap(R.drawable.ic_contact_avatar_mask);
		Bitmap scaleBmp = SimpleUtilities.createScaledIconBitmap(itemInfo.mIcon, mAppIconWidth, mAppIconHeight);
		// 对两个位图做一个遮罩效果
		//FastBitmapDrawable imgDrawable = new FastBitmapDrawable(SimpleUtilities.mask(scaleBmp, maskBmp));
		FastBitmapDrawable imgDrawable = new FastBitmapDrawable(SimpleUtilities.bitmapMask(scaleBmp, maskBmp));
		
		if (checkChildView()){
			mAppIcon.setImageDrawable(imgDrawable);
			mAppIconBg.setImageDrawable(null);
			mAppTitle.setText(itemInfo.title);
		}
		
		info = itemInfo;
		setTag(itemInfo);
		
		// 如果在编辑模式,则显示删除视图
		if (((mContext instanceof SimpleUILauncher)) 
				&& (((SimpleUILauncher)mContext).getMode() == SimpleUILauncher.State.EDIT))
			setRemoveVisibility(View.VISIBLE);
	}
	
	// 申请其它应用图标的BubbleView
	public void applyOtherAppFromBubbleView(SimpleItemInfo itemInfo)
	{
		String strIconBg = ((SimpleUILauncher)mContext).getIconBgString(itemInfo.getPkgName());
		setBackgroundResource(mResource.getIdentifier(strIconBg, "drawable","com.tozed.android.launcher"));// 配置资源
		
		FastBitmapDrawable imgDrawable = generateAppIconFromIconCache(itemInfo);
		
		if (checkChildView()){
			mAppIcon.setImageDrawable(imgDrawable);
			mAppTitle.setText(itemInfo.title);
		}
		
		info = itemInfo;
		setTag(itemInfo);
		
		if (((this.mContext instanceof SimpleUILauncher))
				&& (((SimpleUILauncher) this.mContext).getMode() == SimpleUILauncher.State.EDIT))
			setRemoveVisibility(View.VISIBLE);
	}
	
	// 申请预置的app的BubbleView
	public void applyPresetAppFromBubbleView(SimpleApplicationInfo appInfo)
	{
		if ((appInfo.iconPackage == null)|| (appInfo.iconResource == null)){
			applyOtherAppFromBubbleView(appInfo);
			return;
		}
		
		// 图标背景
		int idIconBg = mResource.getIdentifier(appInfo.iconPackage, "drawable", "com.tozed.android.launcher");
		if (idIconBg <= 0){
			appInfo.iconPackage = ((SimpleUILauncher)mContext).getIconBgString(appInfo.getPkgName());
			idIconBg = mResource.getIdentifier(appInfo.iconPackage, "drawable", "com.tozed.android.launcher");
		}
		setBackgroundResource(idIconBg);
		
		// 应用图标
		int idAppIcon = mResource.getIdentifier(appInfo.iconResource, "drawable", "com.tozed.android.launcher");
		if (checkChildView()){
			if (idAppIcon > 0)
				mAppIcon.setImageResource(idAppIcon);
			else
				mAppIcon.setImageDrawable(generateAppIconFromIconCache(appInfo));
		}
		
		mAppTitle.setText(appInfo.title);
		info = appInfo;
		setTag(appInfo);
		
		if (mContext instanceof SimpleUILauncher
				&& (((SimpleUILauncher)mContext).getMode() == SimpleUILauncher.State.EDIT))
			setRemoveVisibility(View.VISIBLE);
	}
	
	// 是否可删除
	public boolean isRemovable(){
		return (info.itemType == 0 || info.itemType == 1) && !info.isFixedPosition;
	}
	
	@Override
	protected void onDraw(Canvas canvas)
	{
		//Log.e(TAG,">>onDraw isPressed()" + isPressed() + ",mIsTouchMove=" + mIsTouchMove);
		if (isPressed() && !mIsTouchMove){
		//if (isPressed()){
		    drawBubbleOutline(canvas);
		}
		
		super.onDraw(canvas);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		
	    switch (event.getAction())
	    {
	    case MotionEvent.ACTION_MOVE:
	    	//Log.e(TAG,">>onInterceptTouchEvent MotionEvent.ACTION_MOVE.....................");
	    	mIsTouchMove = true;
	    	mPostDrawHandler.removeCallbacks(mDrawOutlineRunnable);
	    	break;
	    	
	    case MotionEvent.ACTION_DOWN:
	      //Log.e(TAG,">>onInterceptTouchEvent MotionEvent.ACTION_DOWN.....................");
	      mPostDrawHandler.postDelayed(mDrawOutlineRunnable, 200);
	      break;
	      
	    case MotionEvent.ACTION_UP: 
	    	//Log.e(TAG,">>onInterceptTouchEvent MotionEvent.ACTION_UP......................");
	    	mIsTouchMove = false;
	    	if (isPressed())
	  	      setPressed(false);
	    	postInvalidate();
	    	break;
	    	
	    case MotionEvent.ACTION_CANCEL:
	    	//Log.e(TAG,">>onInterceptTouchEvent MotionEvent.ACTION_CANCEL......................");
	    	break;
	    }
	    
	    return super.onTouchEvent(event);
	}
	
	// 释放视图资源
	public void recycleBubbleView()
	{
		mRemoveInfo = null;
		mAppIconBg = null;
		
		if ((mAppIcon != null) && ((mAppIcon.getDrawable() instanceof FastBitmapDrawable)))
		{
			FastBitmapDrawable imgDrawable = (FastBitmapDrawable)mAppIcon.getDrawable();
			if ((imgDrawable != null)&& (imgDrawable.getBitmap() != null) && (!imgDrawable.getBitmap().isRecycled()))
				imgDrawable.getBitmap().recycle();
		}
		
		mAppIcon = null;
	}
	
	//  设置应用图标
	public void setAppIcon(Bitmap icon)
	{
		Bitmap maskBmp = SimpleUtilities.getMaskBitmap(R.drawable.ic_icon_mask);
		Bitmap scaleBmp = SimpleUtilities.createScaledIconBitmap(icon, mAppIconWidth, mAppIconHeight);

		//Bitmap resultBmp = SimpleUtilities.mask(scaleBmp, maskBmp);
		Bitmap resultBmp = SimpleUtilities.bitmapMask(scaleBmp, maskBmp);
		if (resultBmp != null){
			FastBitmapDrawable imgDrawable = new FastBitmapDrawable(antiAlias(resultBmp));
			mAppIcon.setImageDrawable(imgDrawable);
		} else {
			Log.e(TAG, "targetBitmap was null in method setAppIcon()");
		}
	}

	public void setAppTitle(String title){
		mAppTitle.setText(title);
	}
	
	// 生成App图标
	public FastBitmapDrawable generateAppIconFromIconCache(SimpleItemInfo itemInfo)
	{
		if (itemInfo.mIcon == null)
			itemInfo.mIcon = SimpleUtilities.makeDefaultIcon(mContext, -1);
		
		Bitmap maskBmp = SimpleUtilities.getMaskBitmap(R.drawable.ic_icon_mask);
		Bitmap scaleBmp = SimpleUtilities.createScaledIconBitmap(itemInfo.mIcon, mAppIconWidth, mAppIconHeight);
		
		//return new FastBitmapDrawable(SimpleUtilities.mask(scaleBmp, maskBmp));
		return new FastBitmapDrawable(SimpleUtilities.bitmapMask(scaleBmp, maskBmp));
	}
	
	public void setRemoveVisibility(int visibility){
	    mRemoveInfo.setVisibility(visibility);
	}
	
	// 设置未读消息
	public void setUnreadNum(int nUnreadNum){
		mUnreadNum = nUnreadNum;
		if (mPostDrawHandler.hasMessages(FLAG_UPDATE_UNREAD))
			mPostDrawHandler.removeMessages(FLAG_UPDATE_UNREAD);
		
		mPostDrawHandler.sendEmptyMessageDelayed(FLAG_UPDATE_UNREAD, 0);
	}

}
